//
//  MILSelectedAlarmTimeViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/16.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILSelectedAlarmTimeViewController.h"
#import "MILSelectedRingsOfBellViewController.h"
#import "CustomTimePicker.h"
#import "SaveAlarmClockApi.h"
#import "TimePicker.h"
#import "FIDPickerView.h"
#import "DTPickerManager.h"

@interface MILSelectedAlarmTimeViewController ()<FIDPickerViewDelegate,TimePickerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIView *myPickerView;
@property (weak, nonatomic) IBOutlet UILabel *myFlickerFrequencyLabel;

@property(nonatomic,strong)FIDPickerView *pickerView;

//存储星期的状态
@property(nonatomic,strong)NSMutableArray *myWeekStatusMutableArray;
//存储闪烁频率的数组
@property(nonatomic,strong)NSMutableArray *myFlickerFrequencyMutableArray;
//闪烁频率对应的索引
@property(nonatomic,assign)int currentIndex;
//选择的时间 格式0945
@property(nonatomic,copy)NSString *mySelectedTimeString;
@property(nonatomic,copy)NSString *hourString;
@property(nonatomic,copy)NSString *minuteString;
@property(nonatomic,copy)NSString *alarmID;
@property(nonatomic,copy)NSString *mySelectedRingIndexString;//铃声索引
@property(nonatomic,strong)NSArray *hourArray;
@property(nonatomic,strong)NSArray *minuteArray;

@end

@implementation MILSelectedAlarmTimeViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark -- UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILSelectedAlarmTimeView];
    //注册通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceStateChange:) name:@"DeviceStateNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(SelectedRingResponse:) name:NOTIFICATION_SELECTEDRING object:nil];



}

- (void)deviceStateChange:(NSNotification *)notify{
    NSString *content = notify.object;
    NSDictionary *dic = notify.userInfo;
    if ([dic[@"backCode"] isEqualToString:@"1803"]){
//        NSString *string = [NSString string];
        if (content.length == 14) {
//            string = [content substringWithRange:NSMakeRange(4, 10)];
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"选择时间"];
    
}

//初始化UI
- (void)initMILSelectedAlarmTimeView
{
    __weak UIView *superView = self.view;
    [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.height.mas_equalTo(190);
        make.width.mas_equalTo(superView);
    }];
//    TimePicker *myPicker = [[TimePicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 216)];
//    myPicker.delegate = self;
//    [self.myPickerView addSubview:myPicker];
    if ([self.myFlagString isEqualToString:@"0"])
    {
        //闪烁频率
        self.currentIndex = 0;
//        myPicker.selectedTimeString = @"12:00";
        self.mySelectedTimeString = @"1200";
        [self.pickerView selectRow:12 inComponent:0 animated:NO];
        [self.pickerView selectRow:0 inComponent:1 animated:NO];
        self.hourString = @"12";
        self.minuteString = @"00";
        self.alarmID = @"0";
//        self.myFlickerFrequencyLabel.text = self.myFlickerFrequencyMutableArray[self.currentIndex];
    }
    else if ([self.myFlagString isEqualToString:@"1"])
    {
        if (self.myDataModel)
        {
            //闪烁频率
            self.currentIndex = [self.myDataModel.twinkle intValue];
            [self.pickerView selectRow:[self.myDataModel.h intValue] inComponent:0 animated:NO];
            [self.pickerView selectRow:[self.myDataModel.m intValue] inComponent:1 animated:NO];
            self.hourString = self.myDataModel.h;
            self.minuteString = self.myDataModel.m;
            self.alarmID = self.myDataModel.alarmID;
            self.mySelectedRingIndexString = self.myDataModel.ring;
            self.myFlickerFrequencyLabel.text = self.myFlickerFrequencyMutableArray[self.currentIndex];
        }
        for (int i = 0; i<7; i++)
        {
            UIButton *myBtn = [self.view viewWithTag:i+1];
            myBtn.selected = [self searchWeekExist:i];
            NSLog(@"%d",[self searchWeekExist:i]);
        }
        
    }
    
    
   
}

//判断是否选中状态
- (BOOL)searchWeekExist:(int)week
{
    if ([@"1" isEqualToString:self.myWeekStatusMutableArray[week]]) {
        return YES;
    }
    return NO;
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    }
    cell.textLabel.text = @"选择铃声";
    if (![self.mySelectedRingIndexString isEqualToString:@""] && self.mySelectedRingIndexString)
    {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"铃声%@",self.mySelectedRingIndexString];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //选择铃声
    MILSelectedRingsOfBellViewController *milSelectedRingsofBellVC = [[MILSelectedRingsOfBellViewController alloc]init];
    [self.navigationController pushViewController:milSelectedRingsofBellVC animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return   1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 90;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 90)];
    
    UIButton *guideBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 40, SCREEN_WIDTH-30, 50)];
    [guideBtn setTitle:@"保存" forState:UIControlStateNormal];
    [guideBtn setBackgroundImage:[UIImage imageNamed:@"tianjiakuang"] forState:UIControlStateNormal];
    [guideBtn addTarget:self action:@selector(saveTimeClickAction) forControlEvents:UIControlEventTouchUpInside];
    
    [myView addSubview:guideBtn];
    
    return myView;
}

#pragma mark -- CustomTimePickerDelegate
- (void)selectedCustomPickerTimeString:(NSString *)timeString
{
    self.mySelectedTimeString = timeString;
}

- (void)FIDPickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        self.hourString = [NSString stringWithFormat:@"%li",(long)row];
    } else if (component == 1) {
        self.minuteString = [NSString stringWithFormat:@"%li",(long)row];
    }

}

#pragma mark -- 按钮点击事件
//保存闹钟
- (void)saveTimeClickAction
{
    if (self.hourString.length==0)
    {
        [SVProgressHUD showErrorWithStatus:@"时间不能为空"];
        return;
    }
    
    //获取星期
    NSString *days = [self dealWithWeek];
    if (days.length == 0 || [days isEqualToString:@"0"])
    {
//        [SVProgressHUD showErrorWithStatus:@"循环日期不能为空"];
//        return;
        days = @"00";
    }
    
    if (self.mySelectedRingIndexString.length==0 || !self.mySelectedRingIndexString || [self.mySelectedRingIndexString isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"铃声未选择"];
        return;
    }

    NSString *codeString = [NSString stringWithFormat:@"%@%@%@%@01%@%@",self.alarmNumberString,[NSString decimalToHexadecimal:[self.hourString intValue]],[NSString decimalToHexadecimal:[self.minuteString intValue]],[NSString decimalToHexadecimal:[days intValue]],[NSString decimalToHexadecimal:self.currentIndex],[NSString decimalToHexadecimal:[self.mySelectedRingIndexString intValue]]];
    NSLog(@"codeString:%@",codeString);
    
    [[WiFiSendDataManager defaultService] settingAddAlarm:self.myDeviceModel.mac value:codeString];

}

//获取星期
- (NSString *)dealWithWeek
{
    
    NSMutableString *str = [[NSMutableString alloc]init];
    [str appendString:@"0"];
    for (int i = 6; i>=0; i--)
    {
        [str appendString:self.myWeekStatusMutableArray[i]];
    }
    return [NSString toDecimalSystemWithBinarySystem:str];
}

//选择星期
- (IBAction)selectedWeekClickAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected)
    {
        //选中置为1
        [self.myWeekStatusMutableArray replaceObjectAtIndex:sender.tag-1 withObject:@"1"];
    }
    else
    {
        //未选中置为0
        [self.myWeekStatusMutableArray replaceObjectAtIndex:sender.tag-1 withObject:@"0"];
    }
    
//    NSLog(@"self.myWeekStatusMutableArray = %@",self.myWeekStatusMutableArray);
}

//选择闪烁频率
- (IBAction)selectedFlickerFrequencyClickAction:(UIButton *)sender
{
    switch (sender.tag)
    {
        case 10:
        {
            //向下
            self.currentIndex--;
            if (0 >= self.currentIndex)
            {
                self.currentIndex = 0;
            }
        }
            break;
        case 11:
        {
            //向上
            self.currentIndex++;
            if (5 <= self.currentIndex)
            {
                self.currentIndex = 5;
            }
        }
            break;
            
        default:
            break;
    }
    
    self.myFlickerFrequencyLabel.text = self.myFlickerFrequencyMutableArray[self.currentIndex];
}

#pragma mark -- 保存闹钟相关处理
//days
- (NSString *)dealWithSelectedWeekWithArray:(NSMutableArray *)weeksArray
{
    NSMutableString *myMutString = [[NSMutableString alloc]init];
    for (int i = 0; i<weeksArray.count; i++) {
        NSString *str = weeksArray[i];
        if ([str isEqualToString:@"1"]) {
            //通过索引返回周几
            [myMutString appendString:[NSString stringWithFormat:@",%d",i]];
        }
    }
    
    return [myMutString substringFromIndex:1];
}

#pragma mark -- 按钮点击
- (void)SelectedRingResponse:(NSNotification *)info
{
    NSDictionary *myDic = info.userInfo;
    self.mySelectedRingIndexString = myDic[@"ring"];
    if (![self.mySelectedRingIndexString isEqualToString:@""] && self.mySelectedRingIndexString)
    {
        [self.myTableView reloadData];
    }
}


#pragma mark -- 懒加载
- (NSMutableArray *)myWeekStatusMutableArray
{
    if (!_myWeekStatusMutableArray)
    {
        
        if ([self.myFlagString isEqualToString:@"1"])
        {
            if (self.mySelectedArray)
            {
                _myWeekStatusMutableArray = [NSMutableArray arrayWithArray:self.mySelectedArray];
            }
            
        }
        else
        {
            _myWeekStatusMutableArray = [NSMutableArray arrayWithArray:@[@"0",@"0",@"0",@"0",@"0",@"0",@"0"]];
        }
    }
    
    return _myWeekStatusMutableArray;
}

- (NSMutableArray *)myFlickerFrequencyMutableArray
{
    if (!_myFlickerFrequencyMutableArray)
    {
        _myFlickerFrequencyMutableArray = [NSMutableArray arrayWithArray:@[@"0秒",@"0.1秒",@"0.2秒",@"0.5秒",@"1秒",@"2秒"]];
    }
    
    return _myFlickerFrequencyMutableArray;
}

- (FIDPickerView *)pickerView
{
    if(!_pickerView)
    {
        UIView *superView = self.view;
        _pickerView = [[FIDPickerView alloc]initWithDataSource:@[self.hourArray,self.minuteArray] detailSource:@[@"时",@"分"]];
        _pickerView.FIDdelegate = self;
        [superView addSubview:_pickerView];
    }
    return _pickerView;
}

- (NSArray *)hourArray
{
    if(!_hourArray)
    {
        _hourArray = [[NSArray alloc]init];
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int i = 0; i < 24; i++) {
            [array addObject:[NSString stringWithFormat:@"%i",i]];
        }
        _hourArray = array;
    }
    return _hourArray;
}
- (NSArray *)minuteArray
{
    if(!_minuteArray)
    {
        _minuteArray = [[NSArray alloc]init];
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int i = 0; i < 60; i++) {
            [array addObject:[NSString stringWithFormat:@"%i",i]];
        }
        _minuteArray = array;
    }
    return _minuteArray;
}


@end
